package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 订单提交
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("要提交的订单：{}", orders);

        ordersService.submit(orders);
        return R.success("订单提交成功");
    }

    /**
     * 移动端展示订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> usePage(int page, int pageSize){
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        Long currentId = BaseContext.getCurrentId();
        wrapper.eq(Orders::getUserId,currentId);
        wrapper.orderByDesc(Orders::getCheckoutTime);
        ordersService.page(pageInfo,wrapper);

        //对象拷贝----records的泛型是Orders，需要重新处理
        BeanUtils.copyProperties(pageInfo, ordersDtoPage,"records");

        //处理records
        List<Orders> records = pageInfo.getRecords();
        //遍历每条record
        List<OrdersDto> list = records.stream().map((item) -> {
            //创建DishDto对象
            OrdersDto ordersDto = new OrdersDto();
            //对象拷贝将item（dish）中的数据拷贝到disDto中
            BeanUtils.copyProperties(item, ordersDto);

            //针对每条record（item）获取对应的用户id。
            Long userId = item.getUserId();
            //根据id查询用户对象
            User user = userService.getById(userId);
            if (user != null){
                //获得对应的用户名称
                String name = user.getName();
                //给ordersDto添加用户名称
                ordersDto.setUserName(name);
            }
            //给ordersDto添加订单细节
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,item.getId());
            List<OrderDetail> detailList = orderDetailService.list(queryWrapper);

            ordersDto.setOrderDetails(detailList);
            //返回此次ordersDto

            return ordersDto;
        }).collect(Collectors.toList());
        //对新的records进行赋值
        ordersDtoPage.setRecords(list);

        return R.success(ordersDtoPage);
    }

    @PostMapping("/again")
    public R<String> addAgain(@RequestBody Orders orders){
        log.info("再来一单，订单id为：{}",orders.getId());
        //根据订单id，从order_detail表中查询到订单内包含的菜品或套餐
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> list = orderDetailService.list(wrapper);

        //遍历订单明细表，将订单名字填充到购物车表中
        List<ShoppingCart> shoppingCarts = list.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item,shoppingCart);
            shoppingCart.setId(null);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            return shoppingCart;
        }).collect(Collectors.toList());

        //将这些菜品或套餐，插入到购物车中
        shoppingCartService.saveBatch(shoppingCarts);
        return R.success("再来一单成功");
    }

    /**
     * 管理端展示订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<OrdersDto>> page(int page, int pageSize,Long number,String beginTime,String endTime){
        log.info("page:{},pageSize:{},number:{},beginTime{},endTime:{}",page,pageSize,number,beginTime,endTime);

        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(number != null,Orders::getNumber,number);
        wrapper.ge(beginTime != null,Orders::getOrderTime,beginTime);
        wrapper.le(endTime != null,Orders::getOrderTime,endTime);
        wrapper.orderByDesc(Orders::getCheckoutTime);
        ordersService.page(pageInfo,wrapper);

        //对象拷贝----records的泛型是Orders，需要重新处理
        BeanUtils.copyProperties(pageInfo, ordersDtoPage,"records");


        //处理records
        List<Orders> records = pageInfo.getRecords();
        //遍历每条record
        List<OrdersDto> list = records.stream().map((item) -> {
            //创建DishDto对象
            OrdersDto ordersDto = new OrdersDto();
            //对象拷贝将item（dish）中的数据拷贝到disDto中
            BeanUtils.copyProperties(item, ordersDto);

            //针对每条record（item）获取对应的用户id。
            Long userId = item.getUserId();
            //根据id查询用户对象
            User user = userService.getById(userId);
            if (user != null){
                //获得对应的用户名称
                String name = user.getName();
                //给ordersDto添加用户名称
                ordersDto.setUserName(name);
            }
            //给ordersDto添加订单细节
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,item.getId());
            List<OrderDetail> detailList = orderDetailService.list(queryWrapper);

            ordersDto.setOrderDetails(detailList);
            //返回此次ordersDto

            return ordersDto;
        }).collect(Collectors.toList());
        //对新的records进行赋值
        ordersDtoPage.setRecords(list);

        return R.success(ordersDtoPage);
    }

    @PutMapping
    public R<String> setStatus(@RequestBody Map map){
        log.info("要修改的id和状态：{}",map);
        int status = (int) map.get("status");
        String id = (String) map.get("id");

        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(id != null,Orders::getId,id);
        updateWrapper.set(Orders::getStatus,status);

        ordersService.update(updateWrapper);

        return R.success("修改成功");
    }
}
